<template>
  <div class="app-container">
    <el-row
      :gutter="15"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handelAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          :disabled="single"
          size="mini"
          @click="handelEdit"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          size="mini"
          @click="handelDel"
        >删除
        </el-button>
      </el-col>
      <!-- inline="true" 控制 el-form-item 横向显示 -->
      <el-form
        :model="queryData"
        ref="queryDataRef"
        :inline="true"
        class="el-form-search"
      >
        <!--并网点名称-->
        <el-form-item
          label="名称"
          prop="connectionPointName"
          class="el-form-search-item"
        >
          <el-input
            clearable
            placeholder="并网点名称"
            v-model.trim="queryData.connectionPointName"
          ></el-input>
        </el-form-item>

        <!--地区-->
        <el-form-item
          label="地区"
          prop="area"
          class="el-form-search-item"
        >
          <treeselect
            v-model="queryData.area"
            :options="areaOptions"
            :normalizer="normalizer"
            placeholder="选择地区"
            style="width: 140px"
          />
        </el-form-item>

        <!--客户-->
        <!-- <el-form-item
          label="客户"
          prop="customerNum"
          class="el-form-search-item"
        >
          <el-select
            clearable
            filterable
            placeholder="请选择客户"
            v-model="queryData.customerNum"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.num"
              :value="item.num"
              :label="item.companyName"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <!--所属变电站-->
        <el-form-item
          label="变电站名称"
          prop="substationNum"
          class="el-form-search-item"
        >
          <el-select
            clearable
            filterable
            placeholder="请选择变电站"
            v-model="queryData.substationNum"
          >
            <el-option
              v-for="item in substationOptions"
              :key="item.num"
              :value="item.num"
              :label="item.substationName"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--搜索、重置按钮-->
        <el-form-item class="el-form-search-item">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="searchQuery"
          >搜索
          </el-button>
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetSearch"
          >重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 列表数据展示 -->
    <el-table
      :data="connPointList"
      :height="tableHeight"
      v-loading="loading"
      border
      stripe
      @selection-change="handelSelectionChange"
      highlight-current-row
    >
      <el-table-column
        type="selection"
        width="55"
      ></el-table-column>
      <el-table-column
        type="index"
        label="#"
        width="50"
      >
        <template slot-scope="scope">
          {{ (queryData.pageNum - 1) * queryData.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="名称"
        prop="connectionPointName"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        label="变电站"
        prop="substation.substationName"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        label="地区"
        prop="ancestorNames"
        width="200"
        align="center"
      ></el-table-column>
      <el-table-column
        label="位置"
        prop="location"

        align="center"
      ></el-table-column>
      <!-- <el-table-column
        label="客户"
        prop="customer.companyName"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="联系人"
        prop="contactName"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="联系方式"
        prop="phone"
        width="100"
        align="center"
      ></el-table-column> -->
      <el-table-column
        label="容量"
        prop="capacity"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="电压等级"
        prop="voltageLevel"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="电流变比"
        prop="currentRatio"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="经度"
        prop="lon"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="维度"
        prop="lat"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
            @click="handelEdit(scope.row)"
          >修改
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="mini"
            @click="handelDel(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryData.pageNum"
      :limit.sync="queryData.pageSize"
      @pagination="getList"
    />

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-dialogDrag
      width="800px"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
      >
        <!-- 第一行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--并网点名称-->
            <el-form-item
              label="名称"
              prop="connectionPointName"
            >
              <el-input
                clearable
                placeholder="并网点名称"
                v-model.trim="formData.connectionPointName"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">

            <el-form-item label="客户" prop="customerNum">
              <el-select
                clearable
                filterable
                placeholder="请选择客户"
                v-model="formData.customerNum"
                class="from-select"
              >
                <el-option
                  v-for="item in customerOptions"
                  :key="item.num"
                  :value="item.num"
                  :label="item.companyName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <!-- 第三行、第四行、第五行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--变电站-->
            <el-form-item
              label="变电站"
              prop="substationNum"
            >
              <el-select
                clearable
                filterable
                placeholder="请选择变电站"
                v-model="formData.substationNum"
                class="from-select"
              >
                <el-option
                  v-for="item in substationOptions"
                  :key="item.num"
                  :value="item.num"
                  :label="item.substationName"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 地区 -->
            <el-form-item
              label="地区"
              prop="area"
            >
              <treeselect
                v-model="formData.area"
                :options="areaOptions"
                :normalizer="normalizer"
                placeholder="选择地区"
              />
            </el-form-item>
            <!-- 位置 -->
            <el-form-item
              label="位置"
              prop="location"
            >
              <el-input
                clearable
                placeholder="输入并网点位置"
                type="textarea"
                :rows="2"
                :maxlength="100"
                resize="none"
                show-word-limit
                v-model.trim="formData.location"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="容量"
              prop="capacity"
            >
              <el-input
                clearable
                placeholder="并网点容量"
                v-model.trim="formData.capacity"
              >
                <template slot="append">MW</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="电压等级"
              prop="voltageLevel"
            >
              <el-select
                v-model="formData.voltageLevel"
                placeholder="并网点电压等级"
                class="from-select"
              >
                <el-option
                  v-for="dict in voltageLevelOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictLabel"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="电流变比"
              prop="currentRatio"
            >
              <el-input
                clearable
                placeholder="并网点电流变比"
                v-model.trim="formData.currentRatio"
              >
                <!-- <template slot="append">KW</template> -->
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--联系人-->
            <el-form-item
              label="联系人"
              prop="contactName"
            >
              <el-input
                clearable
                placeholder="联系人名称"
                v-model.trim="formData.contactName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--联系人-->
            <el-form-item
              label="联系方式"
              prop="phone"
            >
              <el-input
                clearable
                placeholder="联系方式"
                v-model.trim="formData.phone"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第六行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--经度-->
            <el-form-item
              label="经度"
              prop="lon"
            >
              <el-input
                clearable
                placeholder="经度"
                v-model.trim="formData.lon"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--维度-->
            <el-form-item
              label="纬度"
              prop="lat"
            >
              <el-input
                clearable
                placeholder="纬度"
                v-model.trim="formData.lat"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitFormData"
        >提交</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listConnectionPoint,
  addConnectionPoint,
  getConnectionPointByNum,
  editConnection,
  delConnectionPoint,
} from "@/api/maintenance/connectionPoint";
import { listCustomer } from "@/api/maintenance/customer";
import { listArea } from "@/api/maintenance/area";
import { listSubstation } from "@/api/maintenance/substation";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ConnectionPoint",
  components: { Treeselect },
  data() {
    return {
      loading: true,

      /**搜索框 */
      queryData: {
        pageNum: 1,
        pageSize: 30,
        connectionPointName: undefined, //并网点名称
        area: undefined, //地区
        customerNum: undefined, //客户
        substationNum: undefined, //所属变电站
        orderBy: "update_time",
        isAsc: "asc",
      },

      /**表格,列表数据展示 */
      // 表格的高度
      tableHeight: "calc(100vh - 200px)",
      // 表格数据列表
      connPointList: [],
      total: 0,
      ids: [],
      single: true,
      multiple: true,

      /**对话框 */
      //标题
      title: "",
      //是否显示
      open: false,
      //表单数据
      formData: {
        lon: 0,
        lat: 0,
      },
      rules: {
        connectionPointName: [
          { required: true, message: "并网点名称不能为空", trigger: "blur" },
        ],
        customerNum: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        substationNum: [
          {
            required: true,
            message: "变电站不能为空",
            trigger: "blur",
          },
        ],
        capacity: [
          { required: true, message: "容量不能为空", trigger: "blur" },
          {
            validator: this.formValidation.validateNumber,
            message: "只能输入整数或小数",
            trigger: "blur",
          },
        ],
        area: [{ required: true, message: "地区不能为空", trigger: "blur" }],
        lon: [
          {
            required: true,
            validator: this.formValidation.validatorLongitude,
            message: "经度范围：-180~180（保留小数点后十五位）",
            trigger: ["change", "blur"],
          },
        ],
        lat: [
          {
            required: true,
            validator: this.formValidation.validatorLatitude,
            message: "纬度范围：-90~90（保留小数点后十五位）",
            trigger: ["change", "blur"],
          },
        ],
        phone: [
          {
            validator: this.formValidation.validatePhone,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
      },
      customerOptions: [],
      substationOptions: [],
      areaOptions: [],
      voltageLevelOptions: [],
    };
  },
  created() {
    this.getList();
    /**查询客户 */
    listCustomer().then((response) => {
      this.customerOptions = response.rows;
    });
    // 查询地区列表
    listArea().then((response) => {
      this.areaOptions = this.handleTree(
        response.data.filter((item) => item.num !== 1),
        "num"
      );
    });
    listSubstation().then((response) => {
      this.substationOptions = response.rows;
    });
    this.getDicts("zk_voltage_level").then((response) => {
      this.voltageLevelOptions = response.data;
    });
  },
  methods: {
    /**查询列表数据 */
    getList() {
      this.loading = true;
      listConnectionPoint(this.queryData).then((response) => {
        this.connPointList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**重置对对话框form表单 */
    reset() {
      this.formData = {
        lon: 0,
        lat: 0,
      };
      this.resetForm("formDataRef");
      /**查询客户 */
      listCustomer().then((response) => {
        this.customerOptions = response.rows;
      });
      // 查询地区列表
      listArea().then((response) => {
        this.areaOptions = this.handleTree(
          response.data.filter((item) => item.num !== 1),
          "num"
        );
      });
      listSubstation().then((response) => {
        this.substationOptions = response.rows;
      });
    },
    /**新增并网点 */
    handelAdd() {
      this.reset();
      this.title = "新增并网点";
      this.open = true;
    },
    /**修改并网点 */
    handelEdit(row) {
      this.reset();
      this.title = "修改并网点";
      this.open = true;
      const ids = row.num || this.ids[0];
      getConnectionPointByNum(ids).then((response) => {
        this.formData = response.data;
      });
    },
    /**删除并网点 */
    handelDel(row) {
      const ids = row.num || this.ids;
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return delConnectionPoint(ids);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => { });
    },
    /**表格多选监听 */
    handelSelectionChange(val) {
      this.ids = val.map((item) => item.num);
      this.single = this.ids.length != 1;
      this.multiple = !this.ids.length;
    },
    /**搜索框 */
    searchQuery() {
      this.queryData.pageNum = 1;
      this.getList();
    },
    /**重置 */
    resetSearch() {
      this.resetForm("queryDataRef");
      this.searchQuery();
    },
    /**提交对话框 */
    submitFormData() {
      this.$refs["formDataRef"].validate((valid) => {
        if (valid) {
          if (this.formData.num != undefined) {
            // 修改
            editConnection(this.formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.open = false;
            });
          } else {
            // 新增
            addConnectionPoint(this.formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.open = false;
            });
          }
        }
      });
    },
    /**取消对话框 */
    close() {
      this.resetForm("formDataRef");
      this.open = false;
    },
    /** 转换地区数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.num,
        label: node.name,
        children: node.children,
      };
    },
  },
};
</script>
